package com.doeis.uwork.dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.doeis.common.utils.StringUtils;
import com.doeis.uwork.bean.ComparatorRelation;
import com.doeis.uwork.common.Constant;
import com.doeis.uwork.entity.mongo.GroupMsg;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.util.JSON;
import com.voland.core.ServiceException;
import com.voland.core.db.DaoException;
import com.voland.core.db.MongoDao;
import com.voland.core.db.Page;

@Singleton
public class GroupMsgMongoDao extends MongoDao {
		
	/**
	 * 主要在手机界面上对人对指数显示
	 * @param myswitchbaord
	 * @param itemid
	 * @param otherUerid 对方用户编号
	 * @return
	 * @throws ServiceException
	 */
	public Page<GroupMsg> findGroupMsg(String myswitchbaord, Page page, GroupMsg groupMsg)throws DaoException{
		try{
			StringBuffer con = new StringBuffer(" { userId:\""+groupMsg.getUserId()+"\"   ");
			if(groupMsg.getSourceId()!=null){
				con.append(" , sourceId: \""+groupMsg.getSourceId()+"\" ");
			}
			
			if(groupMsg.getImg()!=null){
				con.append(" , img: \""+groupMsg.getImg()+"\" ");
			}
			
			if(groupMsg.getShareid()!=null){
				con.append(" , shareid: \""+groupMsg.getShareid()+"\" ");
			}
			
			
			if(groupMsg.getMsceneType()!=null){
				con.append(" , msceneType: \""+groupMsg.getMsceneType()+"\" ");
			}
			
			con.append(" } ");
			BasicDBObject query = (BasicDBObject)JSON.parse(con.toString());	
			BasicDBObject sort = new BasicDBObject();
			sort.put("created_at", -1);
			return super.querySlice(myswitchbaord, GroupMsg.class, page, query, sort);
		}catch(Exception e){
			throw new DaoException(e);
		}
	}
	
	
	public GroupMsg findGroupMsg(String myswitchbaord,  GroupMsg groupMsg)throws DaoException{
		try{
			StringBuffer con = new StringBuffer(" { userId:\""+groupMsg.getUserId()+"\"   ");
			if(groupMsg.getIdentification()!=null){
				con.append(" , identification: \""+groupMsg.getIdentification()+"\" ");
			}
		
			con.append(" } ");
			BasicDBObject query = (BasicDBObject)JSON.parse(con.toString());	
			return super.read(myswitchbaord, GroupMsg.class,  query);
		}catch(Exception e){
			throw new DaoException(e);
		}
	}
	
	
	/**
	 * 主要在手机界面上对人对指数显示
	 * @param myswitchbaord
	 * @param start //开始页数
	 * @param privateMsg
	 * @return
	 * @throws DaoException
	 */
	public List<GroupMsg> findGroupMsg(String myswitchbaord, Integer start,Integer count, GroupMsg groupMsg)throws DaoException{
		try{
			StringBuffer con = new StringBuffer(" { userId:\""+groupMsg.getUserId()+"\"   ");
			if(groupMsg.getSourceId()!=null){
				con.append(" , sourceId: \""+groupMsg.getSourceId()+"\" ");
			}
			
			if(groupMsg.getImg()!=null){
				con.append(" , img: \""+groupMsg.getImg()+"\" ");
			}
			
			if(groupMsg.getShareid()!=null){
				con.append(" , shareid: \""+groupMsg.getShareid()+"\" ");
			}
			
			
//			if(groupMsg.getMsceneType()!=null){
//				con.append(" , msceneType: \""+groupMsg.getMsceneType()+"\" ");
//			}
			
			con.append(" } ");
			BasicDBObject query = (BasicDBObject)JSON.parse(con.toString());	
			BasicDBObject sort = new BasicDBObject();
			sort.put("created_at", -1);
			
			DBCollection coll = getCollection(myswitchbaord, groupMsg.getClass());
			DBCursor cur;
			if (query != null) {
				cur = coll.find(query);
			} else {
				cur = coll.find();
			}
			
			if (sort != null) {
				cur.sort(sort);
			}
			
			if(start != null){
				if (start.intValue() == 0) {
					cur.limit(count);
				} else {
					if(count != null){
						cur.skip(start).limit(count);
					}else{
						cur.skip(start);
					}
				}
			}

			return toBeanList(cur, GroupMsg.class);
		}catch(Exception e){
			throw new DaoException(e);
		}		
	}
	
	
	
	
	/**
	 * 找出所有胶片（图片）
	 * @return
	 * @throws ServiceException
	 */
	public List<GroupMsg> findGroupMsgByImgSlice(GroupMsg groupMsg) throws DaoException{
		try{			
			List<GroupMsg> result = findGroupMsgByImg(groupMsg);
			ComparatorRelation comparator=new ComparatorRelation("created_at",Constant.ORDER_DESCENDING);
			Collections.sort(result, comparator);
			int totalRecodes = result.size();
			
			Integer start = groupMsg.getPage();
			Integer limit = 15;
			int length = start + limit;
			if (length > totalRecodes) {
				length = totalRecodes;
			}
			List<GroupMsg> list = new ArrayList<GroupMsg>();
			for (int i = start; i < length; i++) {
				list.add(result.get(i));
			}
			
			return list;
		}catch(Exception e){
			throw new DaoException(e);
		}		
	}
	/**
	 * 找出所有胶片（图片）
	 * @return
	 * @throws ServiceException
	 */
	public List<GroupMsg> findGroupMsgByImg(GroupMsg groupMsg) throws DaoException{
		try{			
			String con = " { shareid: \""+groupMsg.getShareid()+"\",sourceType: "+groupMsg.getSourceType()+" }  ";
			BasicDBObject query = (BasicDBObject)JSON.parse(con);
			query.append("userId", groupMsg.getUserId());
			String[] groupByColumns = {"img"};		
			BasicDBObject initial = new BasicDBObject();			
			String reduce = "function(doc, prev) { " +  
//	                "prev.fromUser = doc.fromUser;" +  
//	                "prev.toUser = doc.toUser;" +  
//	                "prev.userId = doc.userId;" +  
//	                "prev.sourceType = doc.sourceType;" +  
//	                "prev.sourceId = doc.sourceId;" +  
//	                "prev.content = doc.content;" +  
	                "prev.created_at = doc.created_at;" +  
	                "prev.img = doc.img;" +  
	                "} ";  		
			return super.groupToList(groupMsg.getSwitchboard_id(), GroupMsg.class, groupByColumns, 
					query, initial, reduce, null);
		}catch(Exception e){
			throw new DaoException(e);
		}		
	}
	
	/**
	 * 根据类型查询
	 * @param groupMsg
	 * @return
	 * @throws DaoException
	 * @author wxy
	 * 2014年12月29日星期一中国标准时间上午10:30:16
	 */
	public List<GroupMsg> findGroupMsgBySourceType(GroupMsg groupMsg) throws DaoException{
		try{			
			String con = " {sourceType: "+groupMsg.getSourceType()+" }  ";
			BasicDBObject query = (BasicDBObject)JSON.parse(con);
			query.append("userId", groupMsg.getUserId());
			//query.append("shareid", groupMsg.getShareid());
			
			String[] groupByColumns = {"sourceId"};		
			BasicDBObject initial = new BasicDBObject();			
			String reduce = "function(doc, prev) { " +  
					"prev.fromUser = doc.fromUser;" +  
	                "prev.toUser = doc.toUser;" +  
	                "prev.userId = doc.userId;" +  
	                "prev.sourceType = doc.sourceType;" +  
	                "prev.sourceId = doc.sourceId;" +  
	                "prev.content = doc.content;" +  
	                "prev.created_at = doc.created_at;" +  
	                "prev.img = doc.img;" +  
	                "} ";
			return super.groupToList(groupMsg.getSwitchboard_id(), GroupMsg.class, groupByColumns, query, initial, reduce, null);
		}catch(Exception e){
			throw new DaoException(e);
		}
	}

	/**
	 * 查询消息列表
	 * @param groupMsg
	 * @param groupByColumns
	 * @return
	 * @throws DaoException
	 * @author wxy 2015年6月9日星期二中国标准时间下午3:05:39
	 */
	public List<GroupMsg> findGroupMsgByGroup(GroupMsg groupMsg, String[] groupByColumns) throws DaoException {

		try {
			BasicDBObject query = new BasicDBObject();
			if (!StringUtils.isBlank(groupMsg.getUserId())) {
				query.put("userId", groupMsg.getUserId());
			}else {
				return new ArrayList<GroupMsg>();
			}
			BasicDBObject initial = new BasicDBObject();
			String reduce = "function(doc, result) { " 
					+ "result.id = doc._id;" 
					+ "result.fromUser = doc.fromUser;"
					+ "result.toUser = doc.toUser;" 
					+ "result.userId = doc.userId;"
					+ "result.sourceType = doc.sourceType;" 
					+ "result.msceneType = doc.msceneType;" 
					+ "result.sourceId = doc.sourceId;" 
					+ "result.shareid = doc.shareid;" 
					+ "result.created_at = doc.created_at;" 
					+ "result.msgType = doc.msgType;" 
					+ "result.content = doc.content;" 
					+ "} ";
			
			return groupToList(groupMsg.getSwitchboard_id(), GroupMsg.class, groupByColumns, query, initial, reduce, null);
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
	
	public List<GroupMsg> findGroupMsgByGroup1(GroupMsg groupMsg, String[] groupByColumns) throws DaoException {
		try {
			BasicDBObject query = new BasicDBObject();
			if (!StringUtils.isBlank(groupMsg.getUserId())) {
				query.put("userId", groupMsg.getUserId());
			}else {
				return new ArrayList<GroupMsg>();
			}
			
			
			DBCollection coll = getCollection(groupMsg.getSwitchboard_id(), GroupMsg.class);
			
			BasicDBObject firstOp = new BasicDBObject();
			
			
			//group
			BasicDBObject group = new BasicDBObject();
			BasicDBObject groupValues = new BasicDBObject();
			for (int i = 0; i < groupByColumns.length; i++) {
				groupValues.put("_id", "$"+groupByColumns[i]);
				//groupValues.put(groupByColumns[i], 1);
			}
			//groupValues.put("_id", val);
			groupValues.put("shareid", new BasicDBObject("$first","$shareid"));
			group.put("$group", groupValues);
			//条件
			BasicDBObject match = new BasicDBObject();
			match.put("$match", query);
			//排序
			BasicDBObject sortValue = new BasicDBObject("created_at", -1);
			BasicDBObject sort = new BasicDBObject("$sort", sortValue);
			BasicDBObject limit = new BasicDBObject("$limit", 20);
			
			AggregationOutput out = coll.aggregate(match,group,sort,limit);
			System.out.println(out);
			System.out.println(out.results().toString().split("shareid").length);
			//return groupToList(groupMsg.getSwitchboard_id(), GroupMsg.class, groupByColumns, query, initial, reduce, null);
			return null;
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}

	public GroupMsg readByCondition(GroupMsg groupMsg) throws Exception {
		BasicDBObject query = new BasicDBObject();
		if (!StringUtils.isBlank(groupMsg.getUserId())) {
			query.put("userId", groupMsg.getUserId());
		}
		if (!StringUtils.isBlank(groupMsg.getShareid())) {
			query.put("shareid", groupMsg.getShareid());
		}
		BasicDBObject sort = new BasicDBObject();
		sort.put("created_at", -1);
		return super.read(groupMsg.getSwitchboard_id(), GroupMsg.class, query, null, sort);
	}
	
	public static void main(String[] args) throws DaoException {
			
		//李国利
		String myswitchbaord = "ff8080814868fbc401486cb5e1d40007";
		String myUserid = "ff8080814868fbc401486cb5e1d40008";
		String shareid = "ff8080814868fbc401486cb5e1d40008";
		GroupMsg groupMsg = new GroupMsg();
		groupMsg.setSwitchboard_id(myswitchbaord);
		groupMsg.setUserId(myUserid);
		groupMsg.setShareid(shareid);
		String[] groupByColumns = { "shareid" };
		
		Injector injector = Guice.createInjector();
		GroupMsgMongoDao mongo = injector.getInstance(GroupMsgMongoDao.class);
		mongo.findGroupMsgByGroup1(groupMsg, groupByColumns);
		/*try {
			System.out.println(mongo.readByCondition(groupMsg));;
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		try {
			List<GroupMsg> reuslt = mongo.findGroupMsgByGroup(groupMsg, groupByColumns);
			System.out.println(reuslt.size());
		} catch (DaoException e) {
			e.printStackTrace();
		}
	}
}
